<template>
    <div class="h-full w-full">
      <SplitPanel :style="{ 'flex-direction': 'row !important' }" class="user-page-box">
        <template #left-content>
          <div class="flex justify-between flex-col h-full">
            <a-input-search
              v-model:value="searchValue"
              style="margin-bottom: 8px"
              placeholder="请输入"
            />
            <Tree
              v-model:expandedKeys="state.expandedKeys"
              auto-expand-parent
              :tree-data="state.deptTree"
              @select="onTreeSelect"
            >
            </Tree>
          </div>
        </template>
        <template #right-content>
          <DynamicTable
            show-index
            :data-request="loadTableData"
            :columns="columns"
          >
            <template #toolbar>
              <a-button type="primary" @click="openMenuModal({})"> <PlusOutlined /> 新增 </a-button>
            </template>
          </DynamicTable>
        </template>
      </SplitPanel>
    </div>
  </template>
  
  <script setup lang="tsx">
    import { ref, reactive, computed, onMounted, h, watch,unref, defineComponent } from 'vue';
    import {
      PlusOutlined,
      EditOutlined,
      DeleteOutlined,
      FileSyncOutlined,
    } from '@ant-design/icons-vue';
    import { Tree, Modal, Alert,message } from 'ant-design-vue';
    import type { FormInstance } from 'ant-design-vue';
    import { baseColumns, type TableListItem, type TableColumnItem} from '@/views/organization/station/columns';
    import type { LoadDataParams } from '@/components/core/dynamic-table';
    import type { TreeDataItem } from '@/core/permission/utils';
    import { SplitPanel } from '@/components/basic/split-panel';
    import { useTable } from '@/components/core/dynamic-table';
    import {
      gePostList,
      deletePost,
      getUserInfo,
      createPost,
      editPost,
      postUsers,
    } from '@/api/organization/station/station';
    import { useFormModal } from '@/hooks/useModal/index';
    import { formatDept2Tree, findChildById, flatTree } from '@/core/permission/utils';
    import { getDepartmentEntityList } from '@/api/organization/depts/depts';
    import { useModal } from '@/hooks/useModal/useModal';
    import stationAuth from '@/views/organization/station/stationAuth.vue';
    import { cloneDeep } from 'lodash-es';
  
    defineOptions({
      name: 'station',
    });
    defineComponent({
      stationAuth
    })
    
    interface State {
      parentId: number[];
      departmentIds: number[];
      originData: any;
      deptTree: TreeDataItem[];
    }
    const [DynamicTable, dynamicTableInstance] = useTable({ formProps: { autoSubmitOnEnter: true } });
    const [ModalRender, modalRef] = useModal();
    const authRef = ref<FormInstance>();
  
    const searchValue = ref('');
    const editDrawerBindValue = reactive({
      orgData: [],
      postItem: {},
    });
    type blankDataType=API.CreatePostParams;
    const blankData:blankDataType={
      id: '',
      name: '',
      code: '',
      orgId: '',
      leader: '',
      pubPostId: '',
      pubPostIdName:'',
      responsibility: '',
      document: '',
      qualification: '',
      postType: '',
      postSort: undefined,
      remark: '',
      IS_ENABLED: 1,
      IS_BUSINESS: 0,
    };
  
    const searchTree = (tree, keyword, includeChildren = false) => {
      const newTree: any = [];
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.title.includes(keyword)) {
          if (!state.parentId.includes(node.key) && node.children && node.children.length) {
            state.parentId.push(node.key);
          }
          newTree.push({
            ...node,
            children: includeChildren ? searchTree(node.children || [], '', true) : [],
          });
        } else if (node.children) {
          const result = searchTree(node.children, keyword, true);
          if (result.length > 0) {
            state.parentId.push(node.key);
            newTree.push({ ...node, children: result });
          }
        }
      }
      return newTree;
    };
  
    watch(
      () => searchValue.value,
      (newVal) => {
        state.deptTree = searchTree(state.originData, newVal, true);
      },
    );
  
    const deptListLoading = ref(false);
  
    const state = reactive<State>({
      parentId: [],
      departmentIds: [],
      deptTree: [],
      originData: [],
    });
  
    const rowSelection = ref({
      selectedRowKeys: [] as number[],
      onChange: (selectedRowKeys: number[], selectedRows: TableListItem[]) => {
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        rowSelection.value.selectedRowKeys = selectedRowKeys;
      },
    });
  
    const openMenuModal = async(record: Partial<TableListItem>)=>{
      editDrawerBindValue.orgData=state.deptTree;
      editDrawerBindValue.postItem=record.id?{...record}:{...blankData};
      ModalRender.show({
        title: `${record.id ? '编辑' : '新增'}岗位`,
        width: '50%',
        // 是否显示右上角确定取消
        defaultExtra: true,
        destroyOnClose: true,
        content: () => {
          return <stationAuth  ref={authRef} defaultData={unref(editDrawerBindValue)}></stationAuth>;
        },
        // 确定方法执行
        onOk: async (values) => {
          const [stationInfo,stationRef] = await authRef.value?.handleSubmit();
          let res = await stationRef.value.validate()
          if (res) {
            const createPostData=cloneDeep(stationInfo);
            if(stationInfo.orgId!==undefined&&stationInfo.orgId.length>0&&Array.isArray(stationInfo.orgId)){
              console.log(createPostData.orgId[0],"stationInfo.orgId11111")
              createPostData.orgId=createPostData.orgId[0];
            }
            createPostData.id=record.id ? record.id:"";
            const result=await (record.id ? editPost : createPost)(createPostData);
            if(result.error===200){
              const msg=record.id ? "修改成功":"新增成功";
              message.success(msg);
              dynamicTableInstance?.reload();
            }
          };
        },
      });
  }; 
    /**
     * 获取部门列表
     */
    const fetchDeptList = async () => {
      deptListLoading.value = true;
      const res = await getDepartmentEntityList().finally(() => (deptListLoading.value = false));
      console.log(res);
      if (res && res.result) {
        const dept = flatTree(res.result);
        state.deptTree = formatDept2Tree(dept, '0');
        state.originData = state.deptTree.map((item) => item);
        state.parentId = [...state.parentId, ...state.deptTree.map((n: any) => Number(n.id))];
        state.departmentIds = state.originData[0].id;
      }
    };
  
    /**
     * @description 表格删除行
     */
    const delRowConfirm = async (id: number) => {
      await deletePost({ id: id }).finally(dynamicTableInstance?.reload);
    };
  
    /**
     * 点击部门
     */
    const onTreeSelect = (selectedKeys: number[]) => {
      state.departmentIds = selectedKeys;
      dynamicTableInstance?.reload?.();
    };
  
    const loadTableData = async (params: LoadDataParams) => {
      const data = await gePostList({
        ...params,
        orgId: state.departmentIds.length ? state.departmentIds[0] : '',
      });
      rowSelection.value.selectedRowKeys = [];
      return {
        list: data?.rows || [],
        pagination: {
          total: data.total,
          size: params.limit,
          page: params.pageNum,
        },
      } as API.TableListResult;
    };
  
    const columns: TableColumnItem[] = [
      ...baseColumns,
      {
        title: '操作',
        width: 350,
        dataIndex: 'ACTION',
        align: 'center',
        actions: ({ record }) => [
          {
            label: '编辑',
            icon: h(EditOutlined),
            onClick: () => openMenuModal(record),
          },
          {
            label: '删除',
            danger: true,
            icon: h(DeleteOutlined),
            popConfirm: {
              title: '你确定要删除吗？',
              onConfirm: () => delRowConfirm(record.id),
            },
          },
        ],
      },
    ];
  
    onMounted(() => {
      fetchDeptList();
    });
  </script>
  
  <style lang="less" scoped>
    @import '@/styles/navTheme.less';
    @classBacks: user-page-box;
    .customSetStyle(@classBacks, background-color, 'content-back-user');
  
    :deep(.ant-tree) {
      flex: 1;
    }
  </style>
  